package cn.stimd.spring.context.support;

import cn.stimd.spring.beans.factory.config.BeanDefinition;
import cn.stimd.spring.beans.factory.config.ConfigurableBeanFactory;
import cn.stimd.spring.beans.factory.support.BeanDefinitionRegistry;
import cn.stimd.spring.beans.factory.support.DefaultListableBeanFactory;
import cn.stimd.spring.context.ApplicationContext;
import cn.stimd.spring.context.ConfigurableApplicationContext;

/**
 * 1、持有一个特定的BeanFactory，不会发生改变
 * 2、实现了BeanDefinitionRegistry接口，允许以多种方式来加载BeanDefinition
 * <p>
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
    private final DefaultListableBeanFactory beanFactory;

    public GenericApplicationContext() {
        this.beanFactory = new DefaultListableBeanFactory();
    }

    // ------------------------------- BeanDefinitionRegistry接口
    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        return this.beanFactory.getBeanDefinition(beanName);
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
    }

    @Override
    public void removeBeanDefinition(String beanName) {
        this.beanFactory.removeBeanDefinition(beanName);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return this.beanFactory.containsBeanDefinition(beanName);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return this.beanFactory.getBeanDefinitionNames();
    }

    // ------------------------------- 重写父类方法
    @Override
    protected void refreshBeanFactory() {
        //NO-OP
    }

    @Override
    public final ConfigurableBeanFactory getBeanFactory() {
        return this.beanFactory;
    }

    @Override
    public void setParent(ApplicationContext parent) {
        super.setParent(parent);
        this.beanFactory.setParentBeanFactory(((ConfigurableApplicationContext) getParent()).getBeanFactory());
    }
}
